package com.anbinh.doctor;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;

import com.anbinh.doctor.model.DataResponse;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GcmRegister {

	public static final String EXTRA_MESSAGE = "message";
	public static final String PROPERTY_REG_ID = "registration_id";
	private static final String PROPERTY_APP_VERSION = "appVersion";

	/**
	 * Substitute you own sender ID here. This is the project number you got
	 * from the API Console, as described in "Getting Started."
	 */
	private final static String SENDER_ID = "895895960417";
	private static final String TAG = "GCMDemo";

	private GoogleCloudMessaging gcm;
	private Context context;
	public static String mGcmId;

	public GcmRegister(final Context context) {
		this.context = context;
	}

	public void newInstance() {
		if (checkPlayServices()) {
			gcm = GoogleCloudMessaging.getInstance(context);
			 mGcmId = getRegistrationId();
			if (mGcmId.length() == 0) {
				new registerInBackground().execute("");
			} else {
				registerGcm(mGcmId);
			}

		} else {
			Log.i(TAG, "No valid Google Play Services APK found.");
		}
	}

	public void registerGcm(String gcm_id) {
		 UserLogin userResponse = Utils.getAccountModel(context,Utils.KEY_USER);
		String token = "";
		if (userResponse == null || userResponse.getData().getToken().isEmpty())
			return;
		token =userResponse.getData().getToken();
		ServerController.getInstance(context).requestRegisterGcm(token, gcm_id,
				new OnRequest<DataResponse>() {

					@Override
					public void onSuccess(DataResponse data) {
						Log.d("onSuccess", data.getResponsecode() + "");
					}

					@Override
					public void onError(int errorCode, String message) {

					}
				});

	}

	private boolean checkPlayServices() {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(context);
		if (resultCode != ConnectionResult.SUCCESS) {
			return false;
		}
		return true;
	}

	public String getRegistrationId() {
		final SharedPreferences prefs = getGCMPreferences(context);
		String registrationId = prefs.getString(PROPERTY_REG_ID, "");
		if (registrationId.length() == 0) {
			Log.i(TAG, "Registration not found.");
			return "";
		}
		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
				Integer.MIN_VALUE);
		int currentVersion = getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Log.i(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}

	private SharedPreferences getGCMPreferences(Context context) {
		return context.getSharedPreferences(context.getClass().getSimpleName(),
				Context.MODE_PRIVATE);
	}

	private static int getAppVersion(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}

	private class registerInBackground extends
			AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {

			String regisId = "";
			try {
				regisId = gcm.register(SENDER_ID);
			} catch (Exception ex) {
			}

			return regisId;
		}

		@Override
		protected void onPostExecute(String result) {
			mGcmId=result;
			storeRegistrationId(context, result.toString());
			registerGcm(result);
			
		}
	}

	private void storeRegistrationId(Context context, String regId) {
		final SharedPreferences prefs = getGCMPreferences(context);
		int appVersion = getAppVersion(context);
		SharedPreferences.Editor editor = prefs.edit();
		editor.putString(PROPERTY_REG_ID, regId);
		editor.putInt(PROPERTY_APP_VERSION, appVersion);
		editor.commit();
		
		
	}

}
